#!/bin/bash

#========= 0.全局变量定义 BEGIN
#==========================================#
#==========================================#
#项目名称
PROJECT_NAME='mobile-fx'
#项目版本文件位置
PROJECT_VERSION_FILE='app.xml'
#当前项目所运行的环境（目前分dev、uat、prd，一共3种）
PROJECT_ENV='uat'


#以数组的形式记录所有配置文件的路径
#不存在配置文件则为ARRAY_CONFIG_FILES变量定义一个空数组 eg: ARRAY_CONFIG_FILES=()
#以冒号分隔，前半段指在git中的位置，后半段指要copy到的位置
CONFIGMAP_ARRAY_CONFIG_PATHS[0]='src/Application/Common/Conf/'${PROJECT_ENV}'-config.php:/data/publish/'${PROJECT_ENV}'/'${PROJECT_NAME}'/Application/Common/Conf/config.php'
CONFIGMAP_ARRAY_CONFIG_PATHS[1]='src/Application/Home/Conf/'${PROJECT_ENV}'-config.php:/data/publish/'${PROJECT_ENV}'/'${PROJECT_NAME}'/Application/Home/Conf/config.php'

#Dockerfile文件路径
DOCKERFILE_PATH="release/docker/Dockerfile"

#镜像生成机的ip
IMAGE_MACHINE_IP='10.23.207.207'
#镜像生成机的port
IMAGE_MACHINE_PORT='2375'


#容器机的ip和端口集合
CONTAINER_MACHINE_ARRAY=()
CONTAINER_MACHINE_ARRAY[0]="10.23.207.207:2375"

#容器运行的端口映射参数
CONTAINER_PORT_PARAMS='--publish 17560:80'
#容器运行的目录卷映射参数
CONTAINER_VOLUME_PARAMS='--volume /data/publish/'${PROJECT_ENV}'/'${PROJECT_NAME}'/Application/Common/Conf/:/app/Application/Common/Conf/ --volume /data/publish/'${PROJECT_ENV}'/'${PROJECT_NAME}'/Application/Home/Conf/:/app/Application/Home/Conf/ --volume /data/publish/'${PROJECT_ENV}'/'${PROJECT_NAME}'/Application/Runtime/Logs/:/app/Application/Runtime/Logs/  --volume /data/publish/'${PROJECT_ENV}'/'${PROJECT_NAME}'/Public/:/app/Public/
'


#镜像仓库harbor的ip全地址
REGISTRY_MACHINE_IP='uhub.service.ucloud.cn'
#镜像仓库的登陆用户名
REGISTRY_HARBOR_USERNAME='windinsky122@163.com'
#镜像仓库的登陆密码
REGISTRY_HARBOR_PASSWORD='xj1qaz@WSX'
#镜像仓库的项目名称
REGISTRY_HARBOR_PROJECT_NAME='clplan'
#==========================================#
#==========================================#
#========= 0.全局变量定义 BEGIN

#========= 1.从pom中获取版本号，生成镜像 BEGIN =========
version=`cat ${PROJECT_VERSION_FILE} |grep -i \<version |sed -n '1p;1q'|awk -F">" '{print $2}'|awk -F"<" '{print $1}'`
is_force=`cat ${PROJECT_VERSION_FILE} |grep -i \<force |sed -n '1p;1q'|awk -F">" '{print $2}'|awk -F"<" '{print $1}'`
if [ "$version"x == ""x ]
then
    echo '无法找到版本号！'
    exit 1
fi
echo "当前项目版本为"${version}
echo "当前强制更新策略为"${is_force}
#========= 1.从pom中获取版本号，生成镜像 END =========


#========= 2.获取当前项目已有镜像的版本，若存在已有镜像且版本号一致，则不执行脚本 BEGIN =========
exist_image_tag=`docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} images|grep -i ${PROJECT_NAME} |grep -v latest|grep -v latest|grep -v none|sort -k 2 -r|sed -n '1p;1q'|awk '{print $2}'`
if [ "$version"x == "$exist_image_tag"x ]
then
    if [ "$is_force"x == "1"x ]
    then
        echo '已存最新版本的tag和此次将要更新的版本一致，但更新策略为'${is_force}'！开始强制更新！'
    else
        echo '已存最新版本的tag和此次将要更新的版本一致，不予执行！'
        exit 1
    fi
fi

echo "=====当前项目版本为"${version}"，镜像机中最新版本为"${exist_image_tag}"，更新策略为"${is_force}"！启动更新====="
#========= 2.获取当前项目已有镜像的版本，若存在已有镜像且版本号一致，则不执行脚本 END =========


#========= 4.生成基于新版本的镜像 BEGIN =========
docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} build -t ${REGISTRY_MACHINE_IP}/${REGISTRY_HARBOR_PROJECT_NAME}/${PROJECT_NAME}:${version} -f ${DOCKERFILE_PATH} .
echo '镜像生成完毕！'
#========= 4.生成基于新版本的镜像 END =========



#========= 5.获取tag为none的废弃镜像（如果有），删除掉 BEGIN =========
none_image_id=`docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} images|grep -i ${PROJECT_NAME} |grep -v latest|grep -v latest|grep -i none|sort -k 2 -r|sed -n '1p;1q'|awk '{print $3}'`
if [ "$none_image_id"x != ""x ]
then
    docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} rmi -f ${none_image_id}
    echo '移除废弃（none）镜像完毕！'
fi
#========= 5.获取tag为none的废弃镜像（如果有），删除掉 BEGIN =========


#========= 6.获取版本号按逆序排序最近的一条，得到repository、tag、image id的值 BEGIN =========
latest_repository=`docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} images|grep -i ${PROJECT_NAME} |grep -v latest|grep -v latest|grep -v none|sort -k 2 -r|sed -n '1p;1q'|awk '{print $1}'`
if [ "$latest_repository"x == ""x ]
then
    echo '无法获取latest_repository！'
    exit 1
fi
echo "latest_repository:"${latest_repository}

latest_tag=`docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} images|grep -i ${PROJECT_NAME} |grep -v latest|grep -v latest|grep -v none|sort -k 2 -r|sed -n '1p;1q'|awk '{print $2}'`
if [ "$latest_tag"x == ""x ]
then
    echo '无法获取latest_tag！'
    exit 1
fi
echo "latest_tag:"${latest_tag}


latest_image_id=`docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} images|grep -i ${PROJECT_NAME} |grep -v latest|grep -v latest|grep -v none|sort -k 2 -r|sed -n '1p;1q'|awk '{print $3}'`
if [ "$latest_tag"x == ""x ]
then
    echo '无法获取latest_image_id！'
    exit 1
fi
echo "latest_image_id:"${latest_image_id}
#========= 6.获取版本号按逆序排序最近的一条，得到repository、tag、image id的值 END =========


#========= 7.执行docker tag命令，将刚刚生成的镜像打上latest的tag标签 BEGIN =========
# docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} tag ${latest_repository}:${latest_tag} ${latest_repository}:"latest"
# echo '生成latest镜像'${latest_repository}':latest完毕'
#========= 7.执行docker tag命令，将刚刚生成的镜像打上latest的tag标签 END =========


#========= 8.将最新的镜像上传至镜像中心harbor BEGIN =========
docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} login -u ${REGISTRY_HARBOR_USERNAME} -p ${REGISTRY_HARBOR_PASSWORD} ${REGISTRY_MACHINE_IP}
if [ "$?"x == "1"x ]
then
    echo '【镜像机】登陆镜像仓库失败'
    exit 1
else
    echo '【镜像机】登陆镜像仓库成功'
fi

docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} push ${latest_repository}:${latest_tag}
if [ "$?"x == "1"x ]
then
    echo 'push镜像【'${latest_repository}':'${latest_tag}'】到镜像仓库发生错误！ '
    exit 1
else
    echo '已成功将镜像【'${latest_repository}':'${latest_tag}'】推送至仓库'
fi


# docker -H ${IMAGE_MACHINE_IP}:${IMAGE_MACHINE_PORT} push ${latest_repository}:"latest"
# if [ "$?"x == "1"x ]
# then
    # echo 'push镜像【'${latest_repository}':latest】到镜像仓库发生错误！ '
    # exit 1
# else
    # echo '已成功将镜像【'${latest_repository}':latest】推送至仓库'
# fi
#========= 8.最新的镜像上传至镜像中心harbor END =========


#==========================================
#========= 循环容器机进行操作BEGIN ========
#==========================================
for container_machine in ${CONTAINER_MACHINE_ARRAY[*]};do

    echo '========================================================'
    echo '=====【容器机'${container_machine}'】发布镜像开始！====='
    echo '========================================================'
    
    
    #========= 9.在容器机上下载最新的镜像 BEGIN =========
    #判断镜像是否已在容器机存在
    docker -H ${container_machine} inspect ${REGISTRY_MACHINE_IP}/${REGISTRY_HARBOR_PROJECT_NAME}/${PROJECT_NAME}:${latest_tag}
    
    #不存在则从镜像仓库下载
    if [ "$?"x == "1"x ]
    then
        docker -H ${container_machine} login -u ${REGISTRY_HARBOR_USERNAME} -p ${REGISTRY_HARBOR_PASSWORD} ${REGISTRY_MACHINE_IP}
        if [ "$?"x == "1"x ]
        then
            echo '【容器机'${container_machine}'】登陆镜像仓库失败'
            exit 1
        else
            echo '【容器机'${container_machine}'】登陆镜像仓库成功'
        fi

        docker -H ${container_machine} pull ${REGISTRY_MACHINE_IP}/${REGISTRY_HARBOR_PROJECT_NAME}/${PROJECT_NAME}:${latest_tag}
    fi
    #========= 9.在容器机上下载最新的镜像 END =========

    
    #========= 10.停止和删除正在运行的镜像容器 BEGIN =========
    run_container_id=`docker -H ${container_machine} ps -a|grep -i ${PROJECT_NAME}|sort -k 2 -r|sed -n '1p;1q'|awk '{print $1}'`
    if [ "$run_container_id"x != ""x ]
    then
        echo '已存在正在运行的镜像容器，正在停止和移除...'
        docker -H ${container_machine} stop ${run_container_id}
        docker -H ${container_machine} rm ${run_container_id}
        echo '停止和删除正在运行的项目镜像容器完毕'
    else
        echo '当前镜像不存在正在运行的容器，无需停止和删除'
    fi
    #========= 10.停止和删除正在运行的镜像容器 END =========
    
    
    #========= 11.容器机将最新的镜像run起来 BEGIN =========
    echo 'docker -H '${container_machine}' run --detach \
      --restart always \
      --name '${PROJECT_ENV}'-'${PROJECT_NAME}'  \
      '${CONTAINER_PORT_PARAMS}' \
      --volume /etc/localtime:/etc/localtime:ro \
      '${CONTAINER_VOLUME_PARAMS}' \
    '${REGISTRY_MACHINE_IP}'/'${REGISTRY_HARBOR_PROJECT_NAME}'/'${PROJECT_NAME}':'${latest_tag}

    run_msg=`docker -H ${container_machine} run --detach \
      --restart always \
      --name ${PROJECT_ENV}-${PROJECT_NAME}  \
      ${CONTAINER_PORT_PARAMS} \
      --volume /etc/localtime:/etc/localtime:ro \
      ${CONTAINER_VOLUME_PARAMS} \
    ${REGISTRY_MACHINE_IP}/${REGISTRY_HARBOR_PROJECT_NAME}/${PROJECT_NAME}:${latest_tag}`

    echo ${run_msg}
    
    
    #========= 3.项目配置文件按环境加载 BEGIN =========
    for config_array_str in ${CONFIGMAP_ARRAY_CONFIG_PATHS[*]};do
    
        OLD_IFS="$IFS" 
        IFS=":"
        config_array=(${config_array_str})
        IFS="$OLD_IFS"

        source_config_path=${config_array[0]}
        goal_config_path=${config_array[1]}
        
        sshpass -f /opt/p.txt scp ${source_config_path} root@10.23.137.146:${goal_config_path}
        echo 'scp拷贝'${source_config_path}'到root@10.23.137.146'${goal_config_path}
    done
    #========= 3.项目配置文件按环境加载 END =========
        
    

    if [ "$run_msg"x == ""x ]
    then
        echo '发布容器出现错误！ '
        exit 1
    else
        echo '已将最新的镜像发布为容器，container id是'${run_msg}
    fi
    #========= 11.容器机将最新的镜像run起来 END =========
    
    
    
    echo '========================================================'
    echo '=====【容器机'${container_machine}'】发布镜像结束！====='
    echo '========================================================'
done
#==========================================
#========= 循环容器机进行操作END ==========
#==========================================

exit 0
